#include "ImportFileDialog.h"
#include <Windows.h>
#include <filesystem>

#define MAX_PATH_LENGTH 2024

namespace SEngine
{
    ImportFileDialog::ImportFileDialog(const std::string &p_dialogTitle)
        : FileDialog(GetOpenFileNameA, p_dialogTitle)
    {
    }
    
    void ImportFileDialog::AddFileType(const std::string &p_label, const std::string &p_filter)
    {
		m_filter += p_label + '\0' + p_filter + '\0';
    }
    
    void ImportFileDialog::Show(EExplorerFlags p_flags)
    {
        char * filePath = (char *)alloca(MAX_PATH_LENGTH);
        filePath[0] = '\0';
        OPENFILENAME ofn;

		if (!m_initialDirectory.empty())
            memcpy_s(filePath, MAX_PATH_LENGTH, m_initialDirectory.c_str(), m_initialDirectory.size() + 1);

		ZeroMemory(&ofn, sizeof(ofn));
		ofn.lStructSize = sizeof(ofn);
		ofn.hwndOwner = NULL;  // If you have a window to center over, put its HANDLE here
		ofn.lpstrFilter = m_filter.c_str();
		ofn.lpstrFile = filePath;
		ofn.nMaxFile = MAX_PATH_LENGTH;
		ofn.lpstrTitle = m_dialogTitle.c_str();

		if (!m_initialDirectory.empty())
			ofn.lpstrInitialDir = m_initialDirectory.c_str();

		ofn.Flags = static_cast<DWORD>(p_flags);

		m_succeeded = m_callback(&ofn);

		if (!m_succeeded) {
			HandleError();
            return;
        }
        char lastCh{'a'};
        std::string temp;
        for (int i = 0; i < MAX_PATH_LENGTH; ++i) {
            char ch = filePath[i];
            if (ch != '\0') {
                temp += ch;
            } else {
                if (lastCh == '\0')
                    break;

                if (m_filepath.empty()) {
                    m_filepath = temp;
                } else {
                    m_fileNames.emplace_back(temp);
                }
                temp.clear();
            }
            lastCh = ch;
        }
        if (m_fileNames.empty()) {
            m_fileNames.emplace_back(std::filesystem::path(filePath).filename().string());
            m_filepath = std::filesystem::path(filePath).parent_path().string();
        }

    }
}